using System;
using UnityEngine;

public class FPBulletMover : MonoBehaviour
{
    private float speed;
    private float startTime = -1;

    private Vector3 startPosition;
    private Vector3 startDirection;
    private Transform selfTrans;

    private bool isInitialized;
    private WindManager WindManager;

    public void Initialization(Transform _startPos, float _speed, WindManager _windManager)
    {
        selfTrans = transform;
        speed = _speed;
        startPosition = _startPos.position;
        startDirection = _startPos.forward;
        isInitialized = true;
        WindManager = _windManager;
    }

    private Vector3 CalculateBulletPosition(float _time)
    {
        Vector3 tmp_Point = startPosition + _time * speed * startDirection;
        Vector3 tmp_GravityVector = _time * _time * 9.81f * Vector3.down;

        Vector3 tmp_V2Wind2Vector3 = new Vector3(WindManager.GetWindValue.x, 0, WindManager.GetWindValue.y);
        Vector3 tmp_WindVector = _time * _time * tmp_V2Wind2Vector3;

        return tmp_Point + tmp_GravityVector + tmp_WindVector;
    }

    private void FixedUpdate()
    {
        if (startTime < 0)
            startTime = Time.time;
        float currentTime = Time.time - startTime;
        float prevTime = currentTime - Time.fixedDeltaTime;
        float nextTime = currentTime + Time.fixedDeltaTime;

        RaycastHit hit;
        Vector3 currentPoint = CalculateBulletPosition(currentTime);

        if (prevTime > 0)
        {
            Vector3 prevPoint = CalculateBulletPosition(prevTime);

            if (Physics.Linecast(prevPoint, currentPoint, out hit))
            {
                OnHit(hit);
            }
        }

        Vector3 nextPoint = CalculateBulletPosition(nextTime);

        if (Physics.Linecast(currentPoint, nextPoint, out hit))
        {
            OnHit(hit);
        }

        Debug.DrawRay(currentPoint, nextPoint - currentPoint, Color.green, 5);
    }

    private void OnHit(RaycastHit hit)
    {
        ShootableObject shootableObject = hit.transform.GetComponent<ShootableObject>();
        if (shootableObject)
        {
            shootableObject.OnHit(hit);
        }

        Destroy(gameObject);
    }

    private void Update()
    {
        if (!isInitialized || startTime < 0) return;
        float tmp_CurrentTime = Time.time - startTime;
        var tmp_CurrentPos = CalculateBulletPosition(tmp_CurrentTime);
        selfTrans.position = tmp_CurrentPos;
    }
}